﻿namespace MEF_Test.Bricks
{
    using System;
    using System.Linq.Expressions;

    /// <summary>
    /// This class is a helper class to handle properties in a more convenient way.
    /// </summary>
    public static class PropertyHelper
    {
        /// <summary>
        /// Gets the name of the member.
        /// </summary>
        /// <typeparam name="T">The class containing the member whose name is requested.</typeparam>
        /// <param name="expression">The lambda expression describing the member.</param>
        /// <returns>A string representation of the member name.</returns>
        public static string MemberName<T>(this Expression<Func<T, object>> expression)
        {
            MemberExpression memberExpression;

            if (expression.Body.NodeType == ExpressionType.Convert)
            {
                memberExpression = ((UnaryExpression)expression.Body).Operand as MemberExpression;
            }
            else
            {
                memberExpression = expression.Body as MemberExpression;                
            }


            if (memberExpression == null)
            {                
                throw new InvalidOperationException("Expression must be a member expression");                                    
            }

            return memberExpression.Member.Name;
        } 
    }
}
